import os
import sys
import inspect
import traceback
from openai import OpenAI
from dotenv import load_dotenv

load_dotenv()

class AIDebugger:
    def __init__(self, model=None,api_key=None,base_url=None):
        self.client = OpenAI(api_key=api_key, base_url=base_url)
        self.model = model
    
    def get_error_context(self):
        """获取错误发生时的上下文信息"""
        tb = sys.exc_info()[2]
        while tb.tb_next:
            tb = tb.tb_next  # 获取最内层的traceback
        
        frame = tb.tb_frame
        filename = frame.f_code.co_filename
        lineno = tb.tb_lineno
        
        # 获取源代码上下文
        try:
            with open(filename, 'r') as f:
                source_code = f.readlines()
            
            # 获取错误行附近的代码
            start_line = max(0, lineno - 5)
            end_line = min(len(source_code), lineno + 5)
            context_code = "".join(source_code[start_line:end_line])
            
            return {
                "filename": filename,
                "lineno": lineno,
                "context_code": context_code,
                "error_line": source_code[lineno-1].strip()
            }
        except:
            return {"error": "无法获取源代码上下文"}
    
    def analyze_error(self, exc_type, exc_value, exc_traceback):
        """发送错误信息给AI分析"""
        error_msg = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
        context = self.get_error_context()
        
        prompt = f"""
        你是一个Python专家，请分析以下错误并给出修复建议，语言一定要精简：

        错误信息:
        {error_msg}

        发生错误的文件: {context.get('filename', '未知')}
        错误行号: {context.get('lineno', '未知')}
        错误行内容: {context.get('error_line', '未知')}

        相关代码上下文:
        {context.get('context_code', '无法获取代码上下文')}

        请用中文回答，格式如下:
        1. 错误原因分析
        2. 修复建议
        3. 修改后的代码示例(如果有必要)
        """
        
        try:
            response = self.client.chat.completions.create(
                model=self.model,
                messages=[{"role": "user", "content": prompt}],
                temperature=0.7
            )
            return response.choices[0].message.content
        except Exception as e:
            return f"无法获取AI分析结果: {str(e)}"
    
    def install_hook(self):
        """安装全局异常钩子"""
        def custom_excepthook(exc_type, exc_value, exc_traceback):
            # 先打印原始错误信息
            sys.__excepthook__(exc_type, exc_value, exc_traceback)
            
            print("\n🤖 AI诊断助手正在分析错误...\n")
            analysis = self.analyze_error(exc_type, exc_value, exc_traceback)
            
            print("="*50)
            print("💡 AI分析结果:")
            print(analysis)
            print("="*50)
        
        sys.excepthook = custom_excepthook

# 使用示例
if __name__ == "__main__":
    debugger = AIDebugger()
    debugger.install_hook()
    
    # 测试代码 - 这里会触发一个错误
    def faulty_function():
        data = {"key": "value"}
        return data["nonexistent_key"]  # 这里会引发KeyError
    
    faulty_function()
